package com.ligq.h265toupinpush.avmetting

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Surface
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import com.ligq.h265toupinpush.R

class MeetingActivity : AppCompatActivity(), IPeerConnection {
    private lateinit var self: LocalSurfaceView
    private val surfaces = mutableListOf<Surface>()
    private val decoders = mutableListOf<MeetingH264Player>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_meeting)
        initView()
    }

    private fun initView() {
        self = findViewById(R.id.sv_self)
        val sv1 = findViewById<SurfaceView>(R.id.sv_1)
        val sv2 = findViewById<SurfaceView>(R.id.sv_2)
        val sv3 = findViewById<SurfaceView>(R.id.sv_3)
        val surfaceViews = mutableListOf<SurfaceView>()
        surfaceViews.add(sv1)
        surfaceViews.add(sv2)
        surfaceViews.add(sv3)
        for (surfaceView in surfaceViews) {
            surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
                override fun surfaceCreated(holder: SurfaceHolder) {
                    surfaces.add(holder.surface)
                }

                override fun surfaceChanged(
                    holder: SurfaceHolder,
                    format: Int,
                    width: Int,
                    height: Int
                ) {
                    Log.d(TAG, "surfaceChanged: ")
                }

                override fun surfaceDestroyed(holder: SurfaceHolder) {
                    Log.d(TAG, "surfaceDestroyed: ")
                }

            })
        }
    }

    fun joinMeeting(view: View) {
        val socketLive = SocketLive(this)
        self.startCapture(socketLive)
        socketLive.start(this)
    }

    var surfaceIndex = 0
    override fun newConnection(remoteIp: String?) {
        val meetingH264Player = MeetingH264Player(remoteIp!!)
        if (surfaceIndex >= surfaces.size) {
            surfaceIndex = 0
        }
        meetingH264Player.initPlayer(surfaces[surfaceIndex++])
        decoders.add(meetingH264Player)

    }

    override fun remoteReceiveData(remoteIp: String?, data: ByteArray?) {
        var matchDecoder: MeetingH264Player? = null
        for (decoder in decoders) {
            if (remoteIp == decoder.ip) {
                matchDecoder = decoder
            }
        }
        matchDecoder?.decode(data!!)
    }
}